﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
using Swift;

public class Settlement : MonoBehaviour {

	public Text t1;
	public Text t2;
	public Text Chapter;

	public GameObject Config;

	// Use this for initialization
	void Start () {
		Config = GameObject.Find ("Config");

		GameDriver driver = Config.GetComponent<GameDriver> ();
		Chapter.text = driver.Chapter + "";
		StartCoroutine (CalculateScore(driver.Pass, driver.Chapter < driver.MaxChapter, driver.Num));
	}

	IEnumerator CalculateScore(bool pass, bool cont, int[,] num) {

		for (int i = 0; i < 4; i++) {
			int wait = 0;
			for (int j = 0; j < 2; j++) {
				StartCoroutine (ShowNum (i, j, num [i, j], ()=>{
					wait ++;
				}));
			}

			while (wait < 2)
				yield return null;
		}

		yield return new WaitForSeconds (3f);

		if (pass && cont == true) {
			SceneManager.LoadScene ("Game");
		} else {
			SceneManager.LoadScene ("UI");
		}

		yield return null;
	}

	// Update is called once per frame
	void Update () {
		t1.text = "Score : " + score1;
		t2.text = "Score : " + score2;
	}

	int score1 = 0;
	int score2 = 0;

	GameObject GetGameObject(string name, int i, int j) {

		return GameObject.Find (name + i + j);

	}
		
	IEnumerator ShowNum(int i, int j, int max, Action callback) {

		yield return null;

		GameObject arrow = GetGameObject ("arrow", i, j);

		int num = -1;

		float d = 225f / (max - num);
		if (j == 0) {
			d = -d;
		}

		float t = 1f / max;

		while (num < max) {
			
			num++;

			Text text = GetGameObject ("num", i, j).GetComponent<Text>();
			text.text = num + "";

			if (num < max) {
				if (j == 0) {
					score1 += (i + 1) * 100;
				} else {
					score2 += (i + 1) * 100;
				}
			}

			RectTransform rect = arrow.GetComponent<RectTransform> ();
			rect.Translate (new Vector3 (d, 0, 0));

			Image img = arrow.GetComponent<Image> ();
			img.color = new Vector4 (img.color.r, img.color.g, img.color.b, img.color.a - t);

			yield return new WaitForSeconds(0.1f);
		}

		callback ();

		yield return null;
	}

}
